<template>
  <div class="page-container">
    <el-card>
      <!-- 搜索栏 -->
      <el-form :model="queryParams" inline>
        <el-form-item label="用户ID：">
          <el-input
            v-model="queryParams.uid"
            placeholder="请输入用户ID"
            :maxLength="200"
            allowClear
            clearable
          />
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入姓名"
            :maxLength="200"
            allowClear
            clearable
          />
        </el-form-item>
        <el-form-item label="手机号：">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入手机号"
            :maxLength="200"
            allowClear
            clearable
          />
        </el-form-item>
        <el-form-item label="审核状态：">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable>
            <el-option label="待审核" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增健康档案</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border stripe>
        <el-table-column prop="fsid" label="档案ID" width="180" />
        <el-table-column prop="userName" label="用户姓名" width="120" />
        <el-table-column prop="userPhone" label="手机号" width="130" />
        <el-table-column prop="name" label="档案姓名" width="120" />
        <el-table-column prop="sex" label="性别" width="80">
          <template #default="{ row }">
            {{ row.sex === '1' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="120" />
        <el-table-column prop="address" label="地址" min-width="180" show-overflow-tooltip />
        <el-table-column prop="checkupDate" label="体检日期" width="120" />
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-else-if="row.status === 1" type="success">已通过</el-tag>
            <el-tag v-else-if="row.status === 2" type="danger">已拒绝</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="primary" @click="handleAudit(row)">审核</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handlePageChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="130px"
        v-loading="formLoading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户ID：" prop="uid">
              <el-input
                v-model="formData.uid"
                placeholder="请输入用户ID"
                :maxLength="200"
                allowClear
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名：" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入姓名"
                :maxLength="200"
                allowClear
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别：" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择性别">
                <el-option label="女" value="0" />
                <el-option label="男" value="1" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期：" prop="birthday">
              <el-date-picker
                v-model="formData.birthday"
                type="date"
                placeholder="请选择出生日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="地址：" prop="address">
          <el-input
            v-model="formData.address"
            placeholder="请输入地址"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="既往病史：" prop="medicalHistory">
          <el-input
            v-model="formData.medicalHistory"
            type="textarea"
            :rows="3"
            placeholder="请输入既往病史"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="海鲜过敏：" prop="seafoodAllergy">
          <el-input
            v-model="formData.seafoodAllergy"
            placeholder="请输入海鲜过敏情况"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="服用保健品：" prop="takeHealthProducts">
          <el-input
            v-model="formData.takeHealthProducts"
            placeholder="请输入服用保健品情况"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="运动频率：" prop="exerciseFrequency">
          <el-input
            v-model="formData.exerciseFrequency"
            placeholder="请输入运动频率"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="饮食风格：" prop="dietaryStyle">
          <el-input
            v-model="formData.dietaryStyle"
            placeholder="请输入饮食风格"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="饮酒情况：" prop="drinkingAlcohol">
          <el-input
            v-model="formData.drinkingAlcohol"
            placeholder="请输入饮酒情况"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="关节疼痛：" prop="jointPain">
          <el-input
            v-model="formData.jointPain"
            placeholder="请输入关节疼痛情况"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="健康目标：" prop="healthGoal">
          <el-input
            v-model="formData.healthGoal"
            type="textarea"
            :rows="3"
            placeholder="请输入健康目标"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="体检日期：" prop="checkupDate">
          <el-date-picker
            v-model="formData.checkupDate"
            type="date"
            placeholder="请选择体检日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="formLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="档案详情" width="800px">
      <el-descriptions :column="2" border v-if="currentDetail">
        <el-descriptions-item label="档案ID">{{ currentDetail.fsid }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.uid }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ currentDetail.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentDetail.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ currentDetail.name }}</el-descriptions-item>
        <el-descriptions-item label="性别">
          {{ currentDetail.sex === '1' ? '男' : '女' }}
        </el-descriptions-item>
        <el-descriptions-item label="出生日期">{{ currentDetail.birthday }}</el-descriptions-item>
        <el-descriptions-item label="体检日期">{{ currentDetail.checkupDate }}</el-descriptions-item>
        <el-descriptions-item label="地址" :span="2">{{ currentDetail.address }}</el-descriptions-item>
        <el-descriptions-item label="既往病史" :span="2">
          {{ currentDetail.medicalHistory }}
        </el-descriptions-item>
        <el-descriptions-item label="海鲜过敏">
          {{ currentDetail.seafoodAllergy }}
        </el-descriptions-item>
        <el-descriptions-item label="服用保健品">
          {{ currentDetail.takeHealthProducts }}
        </el-descriptions-item>
        <el-descriptions-item label="运动频率">
          {{ currentDetail.exerciseFrequency }}
        </el-descriptions-item>
        <el-descriptions-item label="饮食风格">
          {{ currentDetail.dietaryStyle }}
        </el-descriptions-item>
        <el-descriptions-item label="饮酒情况">
          {{ currentDetail.drinkingAlcohol }}
        </el-descriptions-item>
        <el-descriptions-item label="关节疼痛">
          {{ currentDetail.jointPain }}
        </el-descriptions-item>
        <el-descriptions-item label="健康目标" :span="2">
          {{ currentDetail.healthGoal }}
        </el-descriptions-item>
        <el-descriptions-item label="审核状态">
          <el-tag v-if="currentDetail.status === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="currentDetail.status === 1" type="success">已通过</el-tag>
          <el-tag v-else-if="currentDetail.status === 2" type="danger">已拒绝</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="审核原因" v-if="currentDetail.auditReason">
          {{ currentDetail.auditReason }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ currentDetail.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ currentDetail.updateTime }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog v-model="auditVisible" title="审核健康档案" width="500px">
      <el-form :model="auditForm" label-width="100px">
        <el-form-item label="审核结果：">
          <el-radio-group v-model="auditForm.status">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核原因：" v-if="auditForm.status === 2">
          <el-input
            v-model="auditForm.auditReason"
            type="textarea"
            :rows="4"
            placeholder="请输入审核原因"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" :loading="auditLoading" @click="handleAuditSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useTable } from '@/composables/useTable'
import {
  getArchiveList,
  getArchiveDetail,
  createArchive,
  updateArchive,
  deleteArchive,
  auditArchive
} from '@/api/modules/health'
import type { HealthArchive, SaveArchiveParams, AuditArchiveParams } from '@/api/types'

// 表格相关
const {
  loading,
  tableData,
  pagination,
  queryParams,
  handleSearch,
  handleReset,
  handlePageChange,
  handleSizeChange,
  fetchData
} = useTable<HealthArchive>(getArchiveList, {
  uid: undefined,
  name: undefined,
  phone: undefined,
  status: undefined
})

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const formLoading = ref(false)
const currentEditId = ref<string>('')

const formData = reactive<SaveArchiveParams>({
  uid: '',
  name: '',
  birthday: '',
  sex: '',
  address: '',
  medicalHistory: '',
  seafoodAllergy: '',
  takeHealthProducts: '',
  exerciseFrequency: '',
  dietaryStyle: '',
  drinkingAlcohol: '',
  jointPain: '',
  healthGoal: '',
  checkupDate: ''
})

const formRules: FormRules = {
  uid: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthday: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  checkupDate: [{ required: true, message: '请选择体检日期', trigger: 'change' }]
}

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<HealthArchive | null>(null)

// 审核相关
const auditVisible = ref(false)
const auditLoading = ref(false)
const auditForm = reactive<AuditArchiveParams>({
  id: '',
  status: 1,
  auditReason: ''
})

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增健康档案'
  currentEditId.value = ''
  resetFormData()
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: HealthArchive) => {
  dialogTitle.value = '编辑健康档案'
  currentEditId.value = row.fsid
  try {
    formLoading.value = true
    const { data } = await getArchiveDetail(row.fsid)
    Object.assign(formData, {
      uid: data.uid,
      name: data.name,
      birthday: data.birthday,
      sex: data.sex,
      address: data.address,
      medicalHistory: data.medicalHistory,
      seafoodAllergy: data.seafoodAllergy,
      takeHealthProducts: data.takeHealthProducts,
      exerciseFrequency: data.exerciseFrequency,
      dietaryStyle: data.dietaryStyle,
      drinkingAlcohol: data.drinkingAlcohol,
      jointPain: data.jointPain,
      healthGoal: data.healthGoal,
      checkupDate: data.checkupDate
    })
    dialogVisible.value = true
  } catch (error) {
    console.error('getArchiveDetail error:', error)
  } finally {
    formLoading.value = false
  }
}

// 查看
const handleView = async (row: HealthArchive) => {
  try {
    const { data } = await getArchiveDetail(row.fsid)
    currentDetail.value = data
    detailVisible.value = true
  } catch (error) {
    console.error('getArchiveDetail error:', error)
  }
}

// 审核
const handleAudit = (row: HealthArchive) => {
  auditForm.id = row.fsid
  auditForm.status = 1
  auditForm.auditReason = ''
  auditVisible.value = true
}

// 提交审核
const handleAuditSubmit = async () => {
  if (auditForm.status === 2 && !auditForm.auditReason) {
    ElMessage.warning('请输入审核原因')
    return
  }

  try {
    auditLoading.value = true
    await auditArchive(auditForm)
    ElMessage.success('审核成功')
    auditVisible.value = false
    fetchData()
  } catch (error) {
    console.error('auditArchive error:', error)
  } finally {
    auditLoading.value = false
  }
}

// 删除
const handleDelete = (row: HealthArchive) => {
  ElMessageBox.confirm('确定要删除该健康档案吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteArchive(row.fsid)
        ElMessage.success('删除成功')
        fetchData()
      } catch (error) {
        console.error('deleteArchive error:', error)
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    formLoading.value = true

    if (currentEditId.value) {
      // 编辑
      await updateArchive(currentEditId.value, formData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      await createArchive(formData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('handleSubmit error:', error)
  } finally {
    formLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    uid: '',
    name: '',
    birthday: '',
    sex: '',
    address: '',
    medicalHistory: '',
    seafoodAllergy: '',
    takeHealthProducts: '',
    exerciseFrequency: '',
    dietaryStyle: '',
    drinkingAlcohol: '',
    jointPain: '',
    healthGoal: '',
    checkupDate: ''
  })
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped lang="scss">
.page-container {
  .toolbar {
    margin-bottom: 16px;
  }

  .pagination {
    margin-top: 16px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
